/**
 *
 */
package com.beta.restapi.controller;

import com.beta.common.exception.ControllerException;
import com.beta.common.web.ContentType;
import com.beta.em.UserStatus;
import com.beta.em.UserType;
import com.beta.entity.Users;
import com.beta.restapi.internal.Consts;
import com.beta.restapi.internal.annotation.AuthSetting;
import com.beta.restapi.internal.annotation.AuthStrategy;
import com.beta.restapi.internal.auth.AuthResult;
import com.beta.restapi.internal.auth.AuthService;
import com.beta.restapi.request.auth.AuthRequest;
import com.beta.restapi.response.AuthResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.CredentialException;
import javax.validation.Valid;

/**
 * @author vector
 */
@Api(tags = {"Auth"})
@RestController
@RequestMapping(Consts.API_PATH_PREFIX)
public class AuthController extends BaseController {

    @Autowired
    private AuthService authService;

    @ApiResponses({@ApiResponse(code = 201, message = "Create a token", response = AuthResponse.class)})
    @AuthSetting(level = AuthStrategy.ANONYMOUS)
    @PostMapping(value = "/user_token", consumes = {ContentType.JSON}, produces = {ContentType.JSON})
    public Object userToken(@Valid @RequestBody AuthRequest requestBody) {
        try {
            AuthRequest.AuthInfo authInfo = requestBody.getAuth();
            AuthResult authResult = authService.auth(authInfo.getUsername(), authInfo.getPassword());
            AuthResponse authResponse = new AuthResponse();
            authResponse.setJwt(authResult.getToken());
            authResponse.setUserType(authResult.getUserType().getValue());
            if (UserType.COURIER.equals(authResult.getUserType())) {
                authResponse.setActive(true);
            } else {
                Users users = authResult.getSubject();
                authResponse.setActive(UserStatus.ACTIVE.getValue().equals(users.getStatus()));
            }
            return ok(authResponse);
        } catch (AccountNotFoundException e) {
            throw new ControllerException("E00106");
        } catch (CredentialException e) {
            throw new ControllerException("E00105");
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }

    @DeleteMapping(value = "/logout", produces = {"application/json"})
    public Object logout(@RequestHeader(Consts.HEADER_AUTH_KEY) String token) {
        authService.logout(token);
        return ok();
    }

}
